package mk.jug.academy.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import mk.jug.academy.model.Content;
import mk.jug.academy.model.ContentStatus;
import mk.jug.academy.model.Page;

import org.springframework.stereotype.Repository;


/**
 * DAO for the {@link Content} entity model.
 *
 * @author Ice.Penov
 */
@Repository
public class ContentDAO extends GenericDAO<Content> {

	/**
	 * Gets the {@link Content}s, by the given status, with the given boundaries, 
	 * ordering by publish date.
	 */
	public Page<Content> findByStatus(final ContentStatus status, final int start, final int end) {
		return new QueryEMContext<Page<Content>>() {			
			@Override @SuppressWarnings("unchecked")
			public Page<Content> query(EntityManager em) {
				Query query = em.createQuery("Select from mk.jug.academy.model.Content c where c.status = :status order by c.publishDate desc");
				query.setParameter("status", status);
				query.setFirstResult(start);
				query.setMaxResults(end);
				List<Content> list = query.getResultList();
				query = em.createQuery("Select count(c.id) from mk.jug.academy.model.Content c where c.status = :status");
				query.setParameter("status", status);
				return new Page<Content>(initialize(list), (Integer) query.getSingleResult());
			}
		}.result();
	}

	/**
	 * Gets the {@link Content}s, by the given status, with the given boundaries, 
	 * ordering by publish date, for the given creatorID only.
	 */
	public Page<Content> findByStatusAndCreator(final ContentStatus status,
			final int start, final int end, final Long creatorID) {
		return new QueryEMContext<Page<Content>>() {
			@Override @SuppressWarnings("unchecked")
			public Page<Content> query(EntityManager em) {
				Query query = em.createQuery("Select from mk.jug.academy.model.Content c where c.status = :status and c.creatorID = :creatorID order by c.publishDate desc");
				query.setParameter("status", status);
				query.setParameter("creatorID", creatorID);
				query.setFirstResult(start);
				query.setMaxResults(end);
				List<Content> list = query.getResultList();
				query = em.createQuery("Select count(c.id) from mk.jug.academy.model.Content c where c.status = :status and c.creatorID = :creatorID order by c.publishDate desc");
				query.setParameter("status", status);
				query.setParameter("creatorID", creatorID);
				return new Page<Content>(initialize(list), (Integer) query.getSingleResult());
			}
		}.result();
	}

}